package tech.wetech.admin3.sys.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.repository.AooUserRepository;
import tech.wetech.admin3.util.AooJwtUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;

import com.alipay.api.FileItem;

import java.util.Base64;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ScanLoginAliService {
  @Autowired
  private AooUserRepository userRepository;
  @Autowired
  private AooJwtUtil jwtUtil;

  @Value("${alipay.easy.appId}")
  private String appId;
  @Value("${alipay.easy.merchantPrivateKey}")
  private String privateKey;
  @Value("${alipay.easy.aliPayPublicKey}")
  private String alipayPublicKey;

  public String getAddressAli() throws UnsupportedEncodingException {
    String redirectUrl = URLEncoder.encode("https://www.szrdid.com/", "UTF-8");
    String url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + appId + "&scope=auth_user&redirect_uri=" + redirectUrl;
    return url;
  }

  public AooUser alilogin(String code) throws Exception {
    // 初始化SDK
    AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

    // 构造请求参数以调用接口
    AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

    // 设置刷新令牌(刷新令牌时填)
//    request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
    // 设置授权码
    request.setCode(code);
    // 设置授权方式
    request.setGrantType("authorization_code");

    AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
    System.out.println(response.getBody());

    if (response.isSuccess()) {
      System.out.println("拿到access_token---");
      JSONObject alipay_system_oauth_token_response = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_system_oauth_token_response");
      String access_token = alipay_system_oauth_token_response.getString("access_token");
      String openid = alipay_system_oauth_token_response.getString("open_id");
      String userid = alipay_system_oauth_token_response.getString("user_id");
      System.out.println("access_token---" + access_token);
      System.out.println("openid---" + openid);
      System.out.println("userid---" + userid);

      JSONObject res = getUserInfo(access_token);   // 获取用户信息
      if (res == null) {
        throw new Exception("获取用户信息失败");
      }
      // 保存用户信息
      AooUser user = saveUser(res.getString("userid"), res.getString("nickname"),res.getString("avatar"));
      // 生成token
      String token = jwtUtil.generateTokenWx(openid);
      user.setToken(token);
      return user;

    } else {
      System.out.println("调用失败");
      // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
      // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
      // System.out.println(diagnosisUrl);
      return null;
    }
  }

  private AlipayConfig getAlipayConfig() {
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
    alipayConfig.setAppId(appId);
    alipayConfig.setPrivateKey(privateKey);
    alipayConfig.setFormat("json");
    alipayConfig.setAlipayPublicKey(alipayPublicKey);
    alipayConfig.setCharset("UTF-8");
    alipayConfig.setSignType("RSA2");
    return alipayConfig;
  }

  private JSONObject getUserInfo(String accessToken) throws AlipayApiException {
    AlipayClient alipayClient = new DefaultAlipayClient(
      "https://openapi.alipay.com/gateway.do",
      appId,
      privateKey,
      "json",
      "GBK",
      alipayPublicKey,
      "RSA2"
    );
    AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
    AlipayUserInfoShareResponse response = alipayClient.execute(request, accessToken);
    log.info("支付宝用户信息共享接口响应：" + response.getBody());

    if (response.isSuccess()) {
      System.out.println("调用成功");
      JSONObject alipay_user_info_share_response = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_user_info_share_response");
      log.info("支付宝用户信息：" + alipay_user_info_share_response);
      String userid = alipay_user_info_share_response.getString("user_id");
      String avatar = alipay_user_info_share_response.getString("avatar");
      String nickname = alipay_user_info_share_response.getString("nick_name");
      JSONObject result = new JSONObject();
      result.put("userid", userid);
      result.put("avatar", avatar);
      result.put("nickname", nickname);
      log.info("支付宝用户信息：" + result);
      return result;
    } else {
      System.out.println("调用失败");
      return null;
    }
  }


  @Transactional
  public AooUser saveUser(String userid, String nickname, String headimgurl) {
    // 检查数据库中是否已经有这个 userid 字符串的Email
    AooUser user = userRepository.findByEmail(userid);
    if (user == null) {
      // 如果没有，创建一个新的用户
      user = new AooUser();
      user.setEmail(userid);
      user.setUsername(nickname);
      user.setAvatarUrl(headimgurl);
      user = userRepository.save(user);   // 保存并重新获取user对象
    } else {
      // 如果已经有这个 userid，更新 userInfo
      user.setUsername(nickname);
      user.setAvatarUrl(headimgurl);
      userRepository.save(user);
    }
    return user;
  }


}
